package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"strconv"
)

type UsersController struct {
	beego.Controller
}

func (c *UsersController) Get() {

	c.Ctx.WriteString("用户中心")
}
func (c *UsersController) AddUser() {
	c.TplName = "userAdd.html"
}

//处理post请求  获取post提交的数据
func (c *UsersController) DoAddUser() {
	id, err := c.GetInt("id")
	if err != nil {
		c.Ctx.WriteString("传值错误")
		return
	}
	fmt.Printf("类型是%T,id值为%v", id, id)
	username := c.GetString("username")
	password := c.GetString("password")
	hobby := c.GetStrings("hobby")
	fmt.Println(username, password, id, hobby)
	c.Ctx.WriteString("用户名称:" + username + ",用户密码：" + password + ",id为：" + strconv.Itoa(id))
}
func (c *UsersController) EditUser() {
	c.TplName = "userEdit.html"
}

//定义一个User的结构体
type User struct {
	Username string   `form:"username" json:"username"`
	Password string   `form:"password" json:"password"`
	Hobby    []string `form:"hobby" json:"hobby"`
}

//post解析
func (c *UsersController) DoEditUser() {
	u := User{}
	if err := c.ParseForm(&u); err != nil {
		c.Ctx.WriteString("post提交失败")
		return
	}
	fmt.Printf("%#v", u)
	c.Ctx.WriteString("post解析成功")
}

//在 beego 中，如果我们需要返回一个 json 数据的话，需要把数据放在结构体中
func (c *UsersController) GetUser() {
	u := User{
		Username: "张三",
		Password: "1234560",
		Hobby:    []string{"1"},
	}
	//传送json
	c.Data["json"] = u
	c.ServeJSON()
}
